package com.gjintel.business.proj.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.gjintel.auction.business.model.AuctionInfo;
import org.activiti.engine.task.Task;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gjintel.business.proj.dao.IProjectPauseDao;
import com.gjintel.business.proj.model.ProjectBidInfo;
import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.business.proj.model.ProjectPause;
import com.gjintel.business.proj.service.INotifyService;
import com.gjintel.business.proj.service.IProjectInfoService;
import com.gjintel.business.proj.service.IProjectPauseService;
import com.gjintel.business.webcontent.model.WebContent;
import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.constant.ProjectStatus;
import com.gjintel.framework.dataset.model.DataSet;
import com.gjintel.framework.holidayset.service.IHolidaySetService;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.service.impl.BaseServiceImpl;
import com.gjintel.sdk.util.DateUtils;
import com.gjintel.sdk.util.StringUtil;
import com.gjintel.sdk.util.WordHandler;
import com.gjintel.workflow.trade.service.IWorkflowProcessInstanceService;

@Service("projectPauseService")
public class ProjectPauseServiceImpl extends BaseServiceImpl implements IProjectPauseService{
	@Autowired
    private IProjectPauseDao projectPauseDao;
    @Autowired
    private IProjectInfoService projectInfoService;
    @Autowired
    private IWorkflowProcessInstanceService workflowProcessInstanceService;
    @Autowired
    private INotifyService notifySevice;

    @Autowired
    private IHolidaySetService holidaySetService;


	@Override
	@Transactional
	public void saveProjectPause(User user, ProjectPause projectPause, String result) {
		
		ProjectPause p = new ProjectPause();
		p.setPauseTime(new Date());
		p.setProjectId(projectPause.getProjectId());
		p.setReason(projectPause.getReason());
		p.setRequestId(user.getId());
		p.setCategory(projectPause.getCategory());
		p.setResult(result);
		this.saveOrUpdate(p);
		//保存项目暂停类型：
		AuctionInfo pi=this.get(AuctionInfo.class, projectPause.getProjectId());
		pi.setPauseCategeroy(p.getCategory());
		if (!StringUtil.isEmpty(result)) {
			pi.setPauseResult(result);
		}
		this.saveOrUpdate(pi);
        if(!StringUtil.isEmpty(projectPause.getBudgetMenuData())){
			String budgetMenuStr[] = projectPause.getBudgetMenuData().split(",");
			List<String> budgetMenuList = new ArrayList<String>(budgetMenuStr.length);
			Collections.addAll(budgetMenuList, budgetMenuStr);
			// 先得到之前关联的清单数据
			List<Resources> resList = FileResUtil.findResources(p.getId());
			Iterator<Resources> resIt = resList.iterator();
			Resources res = null;
			while(resIt.hasNext()){
				res = resIt.next();
				if(!budgetMenuList.contains(res.getId())){
					this.remove(res);
				}
			}
			InitCacheData.getInstance().initFileData();
			for(String budgetMenuId : budgetMenuStr){
				res = FileResUtil.getResources(budgetMenuId);
				if(res != null && res.getBusinessId() == null){
					res.setBusinessId(p.getId());
					this.saveOrUpdate(res);
				}
			}
		}
          if(projectPause.getCategory().equals("0")){//竞价公示暂停
        	    Task task = workflowProcessInstanceService.findTask(pi.getWorkflowId());
				Map<String, Object> variables = new HashMap<String, Object>();

				Long time = pi.getAuctionStart().getTime();
				time = time - 1 * 60 * 1000;//提前1分钟开始竞价流程
				Date auctionPublishEndTime = new Date(time);
				variables.put("auctionPublishEndTime", StringUtil.getISODate(auctionPublishEndTime));

				time = pi.getAuctionEnd().getTime();
				time = time + 1 * 60 * 1000;//延迟1分钟结束竞价流程
				Date auctionEndTime = new Date(time);//竞价结束时间

				variables.put("auction_end_time", StringUtil.getISODate(auctionEndTime));
				variables.put("manager", "bizmanager");
				workflowProcessInstanceService.complete(task.getId(), variables);
		  } else if(projectPause.getCategory().equals("1")){//中标公示暂停
                Task task = workflowProcessInstanceService.findTask(pi.getWorkflowId());
				Map<String, Object> variables = new HashMap<String, Object>();
				variables.put("manager","bizmanager");
				workflowProcessInstanceService.complete(task.getId(), variables);
		  }

	}

	@Override
	public List<ProjectPause> getPrjectPause(String projectId, String category) { 
		return this.projectPauseDao.getPrjectPause(projectId,category);
	}

	@Override
	public List<ProjectInfo> getProjectList(Page page,ProjectInfo project) {
		  
		return this.projectPauseDao.getProjectList(page, project);
	}


	@Override
    @Transactional
	public void projectRevoke(User user, ProjectPause projectPause,String category) {
		List<ProjectPause> list = this.projectPauseDao.getWorkingProjectPause(category,  projectPause.getProjectId());
		ProjectPause p=list.get(0);
		p.setRevokeReason(projectPause.getRevokeReason());
		p.setAuditorId(user.getId());
		p.setResult(Constant.PROJECT_REVOKE);
		this.saveOrUpdate(p);
		//更改流程状态
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectPause.getProjectId());
			    pro.setPauseResult(p.getResult());//项目撤销
				pro.setPauseCategeroy(p.getCategory());
				pro.setTradeTime(new Date());//交易时间
				//流程处理
				Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
				Map<String, Object> variables = new HashMap<String, Object>();
				//variables.put("teminate", 24);
				variables.put("teminate",ProjectStatus.CANCEL.toString());
				workflowProcessInstanceService.complete(task.getId(), variables);
			//项目跨度
			pro.setEndTime(new Date());
			int allDays=DateUtils.daysBetween(pro.getCreateTime(),pro.getEndTime());
			pro.setAllDays(allDays);
			pro.setCancelReason(p.getRevokeReason());
			this.saveOrUpdate(pro);
	}
	

	@Override
	@Transactional
	public void projectFlow(User user, ProjectPause projectPause,String category) {
		List<ProjectPause> list = this.projectPauseDao.getWorkingProjectPause(category,  projectPause.getProjectId());
		ProjectPause p = list.get(0);
		p.setFlowReason(projectPause.getFlowReason());
		p.setAuditorId(user.getId());
		p.setResult(Constant.PROJECT_FLOW);
		this.saveOrUpdate(p);
		//更改流程状态
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectPause.getProjectId());
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		//取消所有中标人
			ProjectBidInfo pbInfo=new ProjectBidInfo();
			pbInfo.setProjectId(pro.getId());
			List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
			for (ProjectBidInfo pb : bidList) {
				if(pb.getIsMultHit()){
					pb.setIsMultHit(false);//为中标单位
					this.saveOrUpdate(pb);
				}
			}
			//流程处理
			//variables.put("bidTeminate", 16);
			variables.put("bidTeminate", ProjectStatus.FLOW_DOWN.toString());
			
			// 流标公示期
			DataSet dataset = this.get(DataSet.class, Constant.DATASET_ID);
			int publicity = dataset.getFlowPublicity();// 公示天数
			String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetService, new Date(), publicity);// (工作日)公示时间
			try {
				pro.setFlowShowEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publicityDate));
			} catch (ParseException e) {
				e.printStackTrace();
			}// 流标公示结束时间
			variables.put("flowShowTime", StringUtil.getISODate(publicityDate));
			workflowProcessInstanceService.complete(task.getId(), variables);


    	pro.setPauseResult(p.getResult());//项目撤销
    	pro.setPauseCategeroy(p.getCategory());
    	pro.setWinningId(null);//将中标单位赋值为null
    	pro.setWinningName(null);
    	pro.setCancelReason(projectPause.getFlowReason());
    	//项目跨度
    	pro.setTradeTime(new Date());//交易时间
    	pro.setEndTime(new Date());
    	int allDays=DateUtils.daysBetween(pro.getCreateTime(),pro.getEndTime());
		pro.setAllDays(allDays);
		this.saveOrUpdate(pro);
		getFlowWebContent(pro);

	}

	@Override
	@Transactional
	public void projectRestore(User user, ProjectPause projectPause,String category, Date newDate,ProjectInfo pro) {
		List<ProjectPause> list = this.projectPauseDao.getWorkingProjectPause(category,  projectPause.getProjectId());
		ProjectPause p = list.get(0);
		p.setRestoreTime(new Date());
		p.setResult(projectPause.getResult());
		this.saveOrUpdate(p);
		if(p.getCategory().equals("1")){
			pro.setShowEndTime(newDate);
		}else{
			pro.setBidStartTime(newDate);
		}
		
		pro.setPauseResult(p.getResult());
		this.saveOrUpdate(pro);
	}
	
	
	@Override
	@Transactional
	public void pauseAuditNew(User user, ProjectPause projectPause, String category) {
		List<ProjectPause> list = this.projectPauseDao.getWorkingProjectPause(projectPause.getCategory(), projectPause.getProjectId());
		ProjectPause p = list.get(0);
		p.setResult(projectPause.getResult());
		p.setReplay(projectPause.getReplay());
		p.setAuditorId(user.getId());
		this.saveOrUpdate(p);
		// 更改流程状态
		if (p.getResult().equals(Constant.AUDITING_PASS)) {// 暂停审核通过
			AuctionInfo pro = projectInfoService.get(AuctionInfo.class, projectPause.getProjectId());
				if (p.getCategory().equals("1")) {//中標公示中暫停
					pro.setPauseResult(p.getResult());
					pro.setPauseCategeroy(p.getCategory());
					this.saveOrUpdate(pro);
                    //流程处理
					Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
					Map<String, Object> variables = new HashMap<String, Object>();
					variables.put("allowParse2",  true);
					workflowProcessInstanceService.complete(task.getId(), variables);
				} else {//竞价公示中暂停
					pro.setPauseResult(p.getResult());
					pro.setPauseCategeroy(p.getCategory());
					this.saveOrUpdate(pro);
				//	 流程处理
					Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
					Map<String, Object> variables = new HashMap<String, Object>();
					variables.put("allowParse", true);
					workflowProcessInstanceService.complete(task.getId(), variables);
				}
		} else {// 暂停审核不通过
			  AuctionInfo pro = projectInfoService.get(AuctionInfo.class, projectPause.getProjectId());
				if(p.getCategory().equals("1")){//中标公示中暂停
					//流程处理
					Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
					Map<String, Object> variables = new HashMap<String, Object>();
					variables.put("allowParse2", false);
					try {
							workflowProcessInstanceService.complete(task.getId(), variables);
					}catch (Exception e){
						e.printStackTrace();
					}

				}else{//竞价公示中暂停
					//流程处理
					Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
					Map<String, Object> variables = new HashMap<String, Object>();
					variables.put("allowParse", false);
					workflowProcessInstanceService.complete(task.getId(), variables);
				}
				//projectInfo表处理
				pro.setPauseResult(p.getResult());
				pro.setPauseCategeroy(p.getCategory());
				this.saveOrUpdate(pro);
			}
	}
	


	@Override
	public List<ProjectPause> getWorkingProjectPause(String category, String projectId) {
		List<ProjectPause> list = this.projectPauseDao.getWorkingProjectPause(category,projectId);
		return list;
	}
	
	
	/**
	 *  发布流标公告
	 * @param pi
	 */
	private void getFlowWebContent(ProjectInfo pi) {
		// 发布流标公告。
		WordHandler world = new WordHandler();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("project", pi);
		map.put("flowTime", sdf.format(new Date()));
		map.put("flowReason", pi.getCancelReason());
		//公示附件
		String pubResName = "";
		List<Resources> resList = FileResUtil.findResources(pi.getId());
		for (Resources resource : resList) {
			if (resource.getFunctionFlog() == 22) {// 公示附件
				pubResName += "<a href='../web/fileView?resId=" + resource.getId() + "'>" + resource.getOldName()
						+ "</a> ";
			}
		}
		map.put("pubResName", pubResName);		
		world.generateWord("flowNotice.html", map, "flowNotice.html");// worldXmlPath
		File file = new File("flowNotice.html");
		String content = "";
		try {
			content = FileUtils.readFileToString(file, "utf-8");
			file.delete();// 删除生成的文件
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 插入新闻数据
		WebContent web =new WebContent();
		web.setTitle("【"+pi.getCatagoryName()+"】" + pi.getName() + "流标公告");
		web.setContent(content);
		web.setCreaterId(ActivitiMap.SUPERADMIN_ID);
		web.setCreateTime(new Date());
		web.setCreaterName("系统");
		web.setDeptId("1");
		web.setProjectId(pi.getId());
		web.setType("33");
		web.setIsDisplay(0);//显示
		web.setEndShowTime(pi.getFlowShowEndTime());// 设置展示结束时间
		this.saveOrUpdate(web);
	}

}
